/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Activity.h"
#include "TaskQueue.h"
#include "Global.h"
#include "myassert.h"

using namespace Chronos;
using namespace std;


namespace Chronos {

class ActivityTask : public Task {
public:
    ActivityTask(ActivityManager* activityManager_) : activityManager(activityManager_) {}
    void cancel() { activityManager = 0; }
    unsigned int run() {
        if (activityManager == 0) return 0;
        return activityManager->runActivity();
    }
private:
    ActivityManager* activityManager;
};

}


ActivityManager::ActivityManager() : activity(0), task(0) {}

ActivityManager::~ActivityManager() {
    cancelActivity();
}

void ActivityManager::setActivity(Activity* activity_) {
    cancelActivity();
    activity = activity_;
    unsigned int delay = activity->start();
    task = new ActivityTask(this);
    Global<TaskQueue>()->addTask(task, delay);
}

unsigned int ActivityManager::runActivity() {
    ASSERT_NOT_NULL(activity); 
    unsigned int delay = activity->progress();
    if (delay == 0) {
        delete activity;
        activity = 0;
    }
    return delay;
}

bool ActivityManager::cancelActivity() {
    if (activity) {
        activity->cancel();
        delete activity;
        activity = 0;
        task->cancel();
        task = 0;
        return true;
    }
    return false;
}

